Camel Case 4

Sort by

recency

|

544 Discussions

|

  • + 0 comments
    import sys
    while True:
        line=sys.stdin.readline().strip()
        if not line:
            break
        Input=line.split(";")
        operation=Input[0]
        Type=Input[1]
        word=Input[2]
        if operation=="S":
            res=""
            for i in word:
                if i.isupper() and not res:
                    res+=i.lower()
                elif i.isupper() and res:
                    res+=" "+i.lower()
                elif i=="("or i==")":
                    continue
                else:
                    res+=i
            print(res)
        elif operation=="C":
            String=word.split()
            res=String[0].lower()
            if Type=="C":
                res=res.capitalize()
            for i in String[1:]:
                res+=i.capitalize()
            if Type=="M":
                res+="()"
            print(res)
    
  • + 0 comments

    Pypy3 solution

    # Enter your code here. Read input from STDIN. Print output to STDOUT
    def camelCase(str):
        operation, type_, line = str.split(";")
        
        if operation == "S":
            words = []
            temp = ""
            for char in line:
                if char.isupper():
                    if temp:
                        words.append(temp)
                    temp = char.lower()
                else:
                    temp += char
            words.append(temp)
            if type_ == "M":
                words[-1] = words[-1].replace('()', '')
            return " ".join(words)
        
        else:
            words = line.split()
            if type_ == "C":
                return "".join([w.capitalize() for w in words])
            elif type_ == "V":
                return words[0] + "".join([w.capitalize() for w in words[1:]])
            else:
                return words[0] + "".join([w.capitalize() for w in words[1:]]) + "()"
    
    
    if __name__ == "__main__":
        import sys
        input = sys.stdin.read
        lines = input().splitlines()
        
        for line in lines:
            if line.strip():
                print(camelCase(line))
    
  • + 1 comment

    Javascript solution, use readline!

    const readline = require("readline");
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    
    rl.on("line", (input) => {
        processData(input);
    });
    
    function processData(input) {
        let operation = input.slice(0, 1);
        let type = input.slice(2, 3);
        let words = input.slice(4, input.length)
    
        const method = {
            'S': split,
            'C': combine
        };
        
        console.log(method[operation](words, type));
    }
    
    function split(words, type) {
      let output = '';
      for (let i = 0; i < words.length; i++) {
          let char = words[i];
          if (char === '(' || char === ')') continue;
          if (char === char.toUpperCase() && i !== 0) {
              output += ` ${char.toLowerCase()}`;
          } else {
              output += char.toLowerCase();
          }
      }
      
      return output.trim();
    }
    
    function combine(words, type) {
        let output = '';
        for (let i = 0; i < words.length; i++) {
            if (words[i - 1] === ' ' || (i === 0 && type === 'C')) {
                output += words[i].toUpperCase();
            } else if (words[i] !== ' ') {
                output += words[i];
            }
        }
      
        if (type === 'M') {
            output += '()';
        }
        
        return output;
    }
    
  • + 0 comments

    Rust solution: If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    //Camel case functions
    fn split(words: &str) -> String {
        let words = match words.strip_suffix("()") {
            Some(stripped) => stripped,
            None => words,
        };
        let mut chars_iter = words.chars();
        let mut splitted_words = chars_iter
            .next()
            .expect("To have found the first letter")
            .to_lowercase()
            .to_string();
        for letter in chars_iter {
            if letter.is_uppercase() {
                splitted_words.push(' ');
                splitted_words.push_str(&letter.to_lowercase().collect::<String>());
            } else {
                splitted_words.push(letter);
            }
        }
    
        splitted_words
    }
    
    fn combine(words: &str, capitalize: bool) -> String {
        let mut combined_words = if capitalize {
            words
                .chars()
                .next()
                .expect("To have found first letter")
                .to_uppercase()
                .collect::<String>()
        } else {
            words
                .chars()
                .next()
                .expect("To have found first letter")
                .to_string()
        };
    
        let mut index = 1;
        while index < words.len() {
            let letter = words.chars().nth(index).expect("To have found index");
            if letter == ' ' {
                index += 1;
                combined_words.push_str(
                    &words
                        .chars()
                        .nth(index)
                        .expect("To have found index")
                        .to_uppercase()
                        .to_string(),
                )
            } else {
                combined_words.push(letter);
            }
            index += 1;
        }
    
        combined_words
    }
    pub fn treat_input(input: String) {
        let lines: Vec<&str> = input.split("\r\n").collect();
        for line in lines {
            let words: Vec<&str> = line.split(";").collect();
            if words[0] == "S" {
                let word = split(words[2]);
                println!("{}", word);
            }
            if words[0] == "C" {
                let capitalize = words[1] == "C";
                let mut word = combine(words[2], capitalize);
                if words[1] == "M" {
                    word.push_str("()");
                }
                println!("{}", word);
            }
        }
    }
    
    pub fn read_input() {
        let mut input = String::new();
        loop {
            let read_line_result = std::io::stdin().read_line(&mut input);
            match read_line_result {
                Ok(0) => break,
                Ok(_n) => (),
                Err(error) => println!("error: {error}"),
            }
        }
        treat_input(input)
    }
    
    fn main() {
        read_input();
    }
    
  • + 0 comments

    Python solution: If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: [my solutions]https://github.com/VictorLemosR/public_codes/tree/master/Hackerrank/3_month_preparation)

    class camel_case:
    
        def __init__(self):
            self.read_input()
    
        def split(self, word: str):
            splitted_word = word[0].lower()
            word = word[1:]
            for letter in word:
                if (letter =="(") or (letter == ")"):
                    continue
                if letter.upper() == letter:
                    splitted_word += " " + letter.lower()
                else:
                    splitted_word += letter
    
            return splitted_word
    
        def combine(self, words):
            combined_words = ""
            index = 0
            while index < len(words):
                letter = words[index]
                if letter == " ":
                    combined_words += words[index+1].upper()
                    index +=1
                else:
                    combined_words += words[index]
                index += 1
    
            return combined_words
    
        def read_line(self, line):
            if line[0]=="S":
                word = self.split(line[2])
            if line[0] == "C":
                word = self.combine(line[2])
                if line[1] =="M":
                    word += "()"
                if line[1]=="C":
                    word = word[0].upper() + word[1:]
    
            print(word)
    
    
    
        def read_input(self):
            continue_loop = True
            number_of_loops = 0
            while continue_loop & number_of_loops <1e5:
                try:
                    number_of_loops += 1
                    line = input()
                    line = line.strip().split(";")
                    self.read_line(line)
                except EOFError:
                    continue_loop = False
                    
    camel_case()