def binary_string(s):
Write a function that takes a string, converts it to a binary string
where vowels are replaced by 0 and consonants are replaced by 1.
The function should return the binary string.
binary_string("Karen")
'10101'
binary_string("Hello World!")
'10110 10111!'
if __name__ == '__main__':
import doctest
doctest.testmod(verbose = True)
Try something like this. Assuming the name of your string variable is "stringVar".
string binaryString="";
for(int i=0;i<stringVar.Length();i++)
{
if(stringVar == 'a' || stringVar == 'A' || stringVar == 'e') //and so on
{
binaryString[i] = '0';
}
else
{
binaryString[i] = '1';
}
}//end for loop.
print(binaryString);
This should give you the result you are looking for. This is the basic functionality. The rest depends on the language you are coding in.
Hope this helps.
Since you have not specified language in which you want solution, so i am assuming it to be java(from my side ). Although, algorithm will be valid for all languages.
code
public class SO {
public static void main(String[] args) {
String s = "Karen";
char[] arr = s.toCharArray();
StringBuilder binary = new StringBuilder();
for (char c : arr) {
if(Character.isAlphabetic(c)){
if (isVowel(c)) {
binary.append("0");
}else{
binary.append("1");
}
}else{
binary.append(c);
}
}
System.out.println(binary);
}
private static boolean isVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
return true;
}
return false;
}
}
output
When input is
String s = "Karen";
then output is
binary = 10101
and
When input is
String s = "Hello World!";
then output is
binary = 10110 10111!
Related
I'm trying to make a simple function in dart to test on which should remove all vowels from an input string but its seems my code never changes the from the original input. Could anyone help me with this? thanks
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' || temp != 'e' || temp != 'i' || temp != 'o' || temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}
and what my tests shows:
00:02 +0 -1: dog --> dg [E]
Expected: 'dg'
Actual: 'dog'
Which: is different.
Expected: dg
Actual: dog
^
Differ at offset 1
Good first try but there is a much easier way of doing this.
replaceAll should do the trick
String removeVolwels(String s){
return s.replaceAll(RegExp('[aeiou]'),'');
}
https://api.flutter.dev/flutter/dart-core/String/replaceAll.html
To make your code work you should change the || to &&
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' && temp != 'e' && temp != 'i' && temp != 'o' && temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}
The loop keeps repeating the output for the entire span of the word.
I tried initiating the console.write on the inside and outside the loop. I also tried changing the values of the incrementor and the substring.
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i <= wordArray.Length; i++)
{
string theLetter = userWord.Substring(i, 1);
//theLetter = theLetter.ToLower();
string rebuilt = new string(wordArray);
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
Console.WriteLine("Your word is now: {0}", rebuilt);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
}
Console.ReadLine();
the console.write should display it's output only once.
You would need to move your Console.WriteLine outside the loop. Also, your loop condition needs to be changed to avoid the ArgumentOutOfRangeException.
for (int i = 0; i < wordArray.Length; i++)
There is one more error in your code. You are converting userWord to lower case, but you are not storing the result.
userWord.ToLower();
Above line needs to be replaced with
userWord = userWord.ToLower();
Complete Code
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord = userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i < wordArray.Length; i++)
{
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
}
var rebuildWord = new string(wordArray);
Console.WriteLine("Your word is now: {0}", rebuildWord);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
Just for your information, you could achieve the same using Regex as well.
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
var rebuildWord = Regex.Replace(userWord,#"[aeiouAEIOU]","$");
Console.WriteLine("Your word is now: {0}", rebuildWord);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
This is just simple. You should check if the loop is in final iteration before printing.
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i <= wordArray.Length; i++)
{
string theLetter = userWord.Substring(i, 1);
//theLetter = theLetter.ToLower();
string rebuilt = new string(wordArray);
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
if(i==userWord.Length)
{
Console.WriteLine("Your word is now: {0}", rebuilt);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
}
}
Console.ReadLine();
I am getting an error message "not all code paths return a value". Can anybody tell me what I missed?
public string AddLineBreak(string str, int column)
{
if (str == null || str.Length == 0)
return "";
}
You missed what happens if the if isn't true.
public string AddLineBreak(string str, int column)
{
if (str == null || str.Length == 0)
return "";
// What happens if str != null or str.Length != 0?
}
In this case, you can resolve it with a simple return (presuming you know what you want to return, that is):
public string AddLineBreak(string str, int column)
{
if (str == null || str.Length == 0)
return "";
return WhatEver_AddLineBreak_Using_str_and_column_returns;
}
I'm doing this question for my own practice and not sure if I'm doing in the most efficient way. Please share any ideas on improving efficieny and my algorithm.
My Algorithm:
Create three suffix array for each corresponding string.
Creating suffix array: One loop to traverse the string and after that sort the vector using stl library so I believe this preprocessing of string is O(n*nlogn). (How should I reduce the complexity here?)
Then traverse any vector and compare the suffix string of all three input strings and compare with maximum you've.
Code:
string commonLongestSubstring(string str1, string str2, string str3)
{
int length1 = str1.length(), length2 = str2.length(), length3 = str3.length();
if (length1 == 0 || length2 == 0 || length3 == 0)
return "";
vector<string> suffixArray1 = getSuffixArray(str1);
vector<string> suffixArray2 = getSuffixArray(str2);
vector<string> suffixArray3 = getSuffixArray(str3);
string longestCommon = "";
for (int i = 0; i < suffixArray1.size() && i < suffixArray2.size() && i < suffixArray3.size(); ++i) {
string prefix = commonPrefix(suffixArray1[i], suffixArray2[i], suffixArray3[i]);
if (longestCommon.length() < prefix.length())
longestCommon = prefix;
}
return longestCommon;
}
string commonPrefix(string a, string b, string c)
{
string prefix;
for (int i = 0; i < a.length() && i < b.length() && i < c.length(); ++i) {
if (a[i] != b[i] || a[i] != c[i])
break;
prefix = prefix + a[i];
}
return prefix;
}
vector<string> getSuffixArray(string str)
{
int length = str.length();
vector<string> suffixesContainer;
for (int i = 0; i < length; ++i) {
suffixesContainer.push_back(str.substr(i, length));
}
sort(suffixesContainer.begin(), suffixesContainer.end());
return suffixesContainer;
}
Doubts:
How to reduce the complexity of part where I'm preprocessing the suffixArray?
This is for three strings but what if problem size increased to n-strings then this algorithm won't work because then I've to create n-suffixArrays. So how usually we handle that case?
General ideas on how usually we work on solving this type of questions(substrings)?
(Language no barrier)
You can use a generalized suffix array to solve k-common substring problem
Give three strings a,b,c an algorithm like this can be solve in O(length(a) * length(b) * length(c)).
The following algorithm can be rewrite using dinamic programming to improve the performance, but it is a good starting point:
public static void main(final String[] args) {
System.out.println(lcs("hello", "othello", "helicopter"));
}
private static String lcs(final String a, final String b, final String c) {
return recursive_lcs(a, b, c, "");
}
private static String recursive_lcs(final String a, final String b,
final String c, String res) {
// Base case: one of the string is empty
if ((a.length() == 0) || (b.length() == 0) || (c.length() == 0)) {
return res;
}
// Recursive case: find one common character
else if ((a.charAt(0) == b.charAt(0)) && (b.charAt(0) == c.charAt(0))) {
res += a.charAt(0);
// Go to the next character
final String r1 = recursive_lcs(a.substring(1), b.substring(1),
c.substring(1), res);
// Search if exists a longer sequence
final String r2 = findMax(a, b, c, "");
if (r2.length() > r1.length()) {
return r2;
} else {
return r1;
}
}
// Recursive case: no common character.
else {
// Check if is better the computed sequence, or if exists one better
// forward
final String c1 = findMax(a, b, c, "");
if (c1.length() > res.length()) {
return c1;
} else {
return res;
}
}
}
private static String findMax(final String a, final String b,
final String c, final String res) {
// Check all the possible combinations
final String c1 = recursive_lcs(a, b, c.substring(1), res);
final String c2 = recursive_lcs(a, b.substring(1), c, res);
final String c3 = recursive_lcs(a.substring(1), b, c, res);
if (c1.length() > c2.length()) {
if (c1.length() > c3.length()) {
return c1;
} else {
return c3;
}
} else {
if (c2.length() > c3.length()) {
return c2;
} else {
return c3;
}
}
}
Output:
hel
I have a problem in which I have to SWAP or move characters and integers. Like I have any characters A . now I have some cases, like
NOTE:- Have to use characters A-Z and integers 0-9
A, now I want that when my program run I assign some integer value to this character, If I assign value 3 to this character then A will become D or it just move to 3 places.
Now if I have a character like Y and I add 4 then it will become C means after Z it will again start from character A.
Same condition I have to follow with Integer if i have 9 and we assign 3 to it then it will become 2 because loop start from 0 not from 1. Means we have to use only 0-9 integers.
I know that i am using wrong name to question but i have no idea that what lines i have to use for that kind of question.
Hope you understand my problem.
Thanks in advance.
Try the below extension method, which does the following:
It creates 2 dictionaries in order to speed up the key look up in the alphabet
Will parse the inputString variable, split it in substrings of the length of the moveString variable's length (or the remainder)
On every substring, it will evaluate each character in order to detect if it's a digit
If it's not a digit, it looks up for the value in the swappedAlphabet dictionary, by using the int key
If it's a digit, it applies a modulo operation on the sum of the digit and the corresponding moveint value
It finally aggregates all the characters in the final result string
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string inputString = "ABC123D", moveString = "12";
var result = inputString.Swap(alphabet, moveString);
Console.WriteLine(result);
}
}
static class ExtensionMethods
{
public static Dictionary<TValue, TKey>
SwapKeysValues<TKey, TValue>(this Dictionary<TKey, TValue> input)
{
var result = new Dictionary<TValue, TKey>();
input.ToList().ForEach((keyValuePair) =>
{
result.Add(keyValuePair.Value, keyValuePair.Key);
});
return result;
}
public static string Swap(
this string input,
string alphabet,
string move)
{
Dictionary<char, int>
alphabetDictionary = new Dictionary<char, int>();
for (int i = 0; i < alphabet.Length; i++)
{
alphabetDictionary.Add(alphabet[i], i);
}
var swapedAlphabet = alphabetDictionary.SwapKeysValues();
return Enumerable
.Range(0, (int)Math.Ceiling(input.Length / (move.Length * 1M)))
.ToList()
.Aggregate<int, string>("", (s, i) =>
{
var l = i * move.Length + move.Length;
var cInput = input.Substring(i * move.Length,
(l > input.Length)
? input.Length - i * move.Length : move.Length);
return s + cInput
.Select((c, index) =>
{
int intCandidate;
if (!Int32.TryParse(c.ToString(), out intCandidate))
{
var length = (alphabetDictionary[c] +
Int32.Parse(move[index].ToString()));
return
swapedAlphabet[(alphabet.Length > length)
? length : length % alphabet.Length];
}
else
{
var moveInt = Int32.Parse(move[index].ToString());
return Char.Parse(((intCandidate + moveInt) % 10)
.ToString());
}
})
.Aggregate<char, string>("", (a, b) => a + b);
});
}
}
Another alternative you have is relying on the in-built character/integer types which follow the order you want; with an additional consideration: if you account for caps, it would deliver caps ("B" after "A" and "b" after "a"). The only thing you need to worry about is making sure that the iterations will be limited to the A-Z/0-9 boundaries. Sample code:
public string moveChar(string inputChar, int noPos)
{
string outChar = checkBoundaries(inputChar, noPos);
if (outChar == "")
{
outChar = basicConversion(inputChar, noPos);
}
return outChar;
}
public string basicConversion(string inputChar, int noPos)
{
return Convert.ToString(Convert.ToChar(Convert.ToInt32(Convert.ToChar(inputChar)) + noPos));
}
public string checkBoundaries(string inputChar, int noPos)
{
string outString = "";
int count1 = 0;
do
{
count1 = count1 + 1;
string curTemp = basicConversion(inputChar, 1);
if (inputChar.ToLower() == "z" || curTemp.ToLower() == "z")
{
if (inputChar.ToLower() != "z")
{
noPos = noPos - count1;
}
inputChar = "a";
outString = "a";
if (inputChar == "Z" || curTemp == "Z")
{
inputChar = "A";
outString = "A";
}
count1 = 1;
}
else if (inputChar == "9" || curTemp == "9")
{
if (inputChar != "9")
{
noPos = noPos - count1;
}
inputChar = "0";
outString = "0";
count1 = 1;
}
else
{
inputChar = curTemp;
outString = inputChar;
}
} while (count1 < noPos);
return outString;
}
It expects strings (just one character (letter or number) per call) and you can call it simply by using: moveChar("current letter or number", no_of_pos_to_move). This version accounts just for "positive"/"forwards" movements but it might easily be edited to account for the inverse situation.
Here's a very simple way to implement a Caesar Cipher with the restrictions you defined.
var shift = 3;
var input = "HELLO WORLD 678";
var classAlphabets = new Dictionary<UnicodeCategory, string>
{
{ UnicodeCategory.SpaceSeparator, " " },
{ UnicodeCategory.UppercaseLetter, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ UnicodeCategory.DecimalDigitNumber, "0123456789" }
};
var encoded = input.ToUpperInvariant()
.Select(c => new { Alphabet = classAlphabets[Char.GetUnicodeCategory(c)], Character = c })
.Select(x => new { x.Alphabet, Index = x.Alphabet.IndexOf(x.Character) })
.Select(x => new { x.Alphabet, Index = x.Index + shift })
.Select(x => new { x.Alphabet, Index = x.Index % x.Alphabet.Length })
.Select(x => x.Alphabet.ElementAt(x.Index))
.Aggregate(new StringBuilder(), (builder, character) => builder.Append(character))
.ToString();
Console.Write(encoded);
// encoded = "KHOOR ZRUOG 901"
Decoding is simply a case of inverting the shift.
Caesar cipher can be easier like this:
static char Encrypt(char ch, int code)
{
if (!char.IsLetter(ch))
{
return ch;
}
char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)(((ch + code - offset) % 26) + offset);
}
static string Encrypt(string input, int code)
{
return new string(input.ToCharArray().Select(ch => Encrypt(ch, code)).ToArray());
}
static string Decrypt(string input, int code)
{
return Encrypt(input, 26 - code);
}
const string TestCase = "Pack my box with five dozen liquor jugs.";
static void Main()
{
string str = TestCase;
Console.WriteLine(str);
str = Encrypt(str, 5);
Console.WriteLine("Encrypted: {0}", str);
str = Decrypt(str, 5);
Console.WriteLine("Decrypted: {0}", str);
Console.ReadKey();
}