A Needle in the Haystack "a coding question ask in gfg" - python

qsn body:-
Given 2 strings Needle and Haystack. The given Needle is distorted in nature and can be shuffled and rearranged in any order. You have to check whether the Needle is part of the Haystack or not. ie- the given string needle is a shuffled substring of string haystack or not.
Input:
First line of input contains number of testcases T. For each test case, first line consists of the needle and second line consists of the haystack.
Output:
Print Yes if the given string needle is a shuffled substring of haystack. Otherwise print No.
Your Task:
Complete the function isShuffledSubstring() that takes the given needle and haystack as input and returns a boolean value.
Constraints:
1 <= haystack.length() <= 1000
1 <= needle.length() <= 1000
Example:
Sample Input:
onetwofour hellofourtwooneworld
roseyellow yellow
geekforgeeks ekegorfkeegsgeek
Sample Output:
Yes
No
Yes
Explanation:
Testcase 1 :
needle onetwofour can be rearranged as fourtwoone which is a substring of haystack hellofourtwooneworld.
Testcase 2 :
Length of needle is greater than haystack. Hence needle is not a substring of haystack.
Testcase 3 :
needle geekforgeeks can be rearranged as orfkeegsgeek which is a substring of haystack ekegorfkeegsgeek.
**required function ==:- **
def isShuffledSubstring(needle, haystack):
# Your code goes here
if len(needle)>len(haystack):
return False
Map1={}
Map2={}
for i in needle:
if i in Map1:
Map1[i]+=1
else:
Map1[i]=1
for i in haystack:
if i in Map2:
Map2[i]+=1
else:
Map2[i]=1
for i in Map1:
if i in Map2:
if Map2[i]<Map1[i]:
return False
else:
return False
return True
it passed test cases but not full test cases.
Sorry,All the test cases are not with me as it is part of coding competition.
Thank You!

bool check(unordered_map<char,int> &_map)
{
bool flag = true;
for(auto i = _map.begin(); i!= _map.end(); i++)
{
if(i->second !=0)
{
flag = false;
break;
}
}
return flag;
}
bool isShuffledSubstring(string needle, string haystack)
{
int len1 = needle.length();
int len2 = haystack.length();
if(len1>len2)
{
return false;
}
unordered_map<char,int> _map;
for(int i=0;i<len1;i++)
{
if(_map.find(needle[i]) == _map.end())
{
_map.insert(make_pair(needle[i],1));
}
else
{
_map[needle[i]] +=1;
}
}
for(int i=0;i<len1;i++)
{
if(_map.find(haystack[i]) != _map.end())
{
_map[haystack[i]] -=1;
}
}
if(check(_map))
{
return true;
}
int i = 0;
int j= len1;
while(j<len2)
{
if(_map.find(haystack[i]) != _map.end())
{
_map[haystack[i]] +=1;
}
if(_map.find(haystack[j]) != _map.end())
{
_map[haystack[j]] -= 1;
if(check(_map))
{
return true;
}
}
i++;
j++;
}
return false;
}

Related

Kotlin set Array as key for a HashMap

I'm doing a bit of Leetcode, and I'm facing this issue: Group Anagrams, I have a Python background and I can do the following:
res = defaultdic(list)
count = [0] * 26
res[tuple(count)].append(s)
as we can see we can set the tupled array as the key for the dictionary, I want to do the same thing in Kotlin, however, when creating this in Kotlin, I get a different object every time when adding this logic in a for loop.
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val hashMap = hashMapOf<IntArray, ArrayList<String>>()
for (word in strs) {
val array = IntArray(26) { 0 }
for (char in word) {
val charInt = char - 'a'
array[charInt] += 1
}
if (hashMap.containsKey(array)) {
hashMap[array]!!.add(word)
} else {
hashMap[array] = ArrayList<String>().apply { add(word) }
}
}
return hashMap.values.toList()
}
Is this something can be done in Kotlin?
Equality for IntArray is checked based on its reference. You can use a List here in place of IntArray. Two Lists are equal if they contain the same elements.
Modified code will be like this:
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val hashMap = hashMapOf<List<Int>, ArrayList<String>>()
for (word in strs) {
val array = List(26) { 0 }.toMutableList()
for (char in word) {
val charInt = char - 'a'
array[charInt] += 1
}
if (hashMap.containsKey(array)) {
hashMap[array]!!.add(word)
} else {
hashMap[array] = ArrayList<String>().apply { add(word) }
}
}
return hashMap.values.toList()
}
Avoiding the problem you run into (equality of arrays) by using String keys:
fun groupAnagramsWithHashing(strs: Array<String>): List<List<String>> {
val map = hashMapOf<String, MutableList<String>>()
MessageDigest.getInstance("SHA-1").also { sha ->
for (word in strs) {
word.toByteArray().sorted().forEach { sha.update(it) }
val key = sha.digest().joinToString()
map.computeIfAbsent(key) { mutableListOf() }.add(word)
}
}
return map.values.toList()
}
fun main() {
val input = arrayOf("eat", "tea", "tan", "ate", "nat", "bat")
groupAnagramsWithHashing(input).also { println(it) }
// [[eat, tea, ate], [bat], [tan, nat]]
}

Use python to rewrite if-else statements like javascript object literals

Here is an example of if-else statement in javascript.
function getTranslation(rhyme) {
if (rhyme.toLowerCase() === "apples and pears") {
return "Stairs";
} else if (rhyme.toLowerCase() === "hampstead heath") {
return "Teeth";
} else if (rhyme.toLowerCase() === "loaf of bread") {
return "Head";
} else if (rhyme.toLowerCase() === "pork pies") {
return "Lies";
} else if (rhyme.toLowerCase() === "whistle and flute") {
return "Suit";
}
return "Rhyme not found";
}
A more elegant way is to rewrite the if-else implementation using object.
function getTranslationMap(rhyme) {
const rhymes = {
"apples and pears": "Stairs",
"hampstead heath": "Teeth",
"loaf of bread": "Head",
"pork pies": "Lies",
"whistle and flute": "Suit",
};
return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}
Can python be used to write similar elegant code like javascript object literals?
I am using python 3.8
Javascript code segment is from link below;
https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0
Python equivalent:
def get_translation_map(rhyme):
rhymes = {
"apples and pears": "Stairs",
"hampstead heath": "Teeth",
"loaf of bread": "Head",
"pork pies": "Lies",
"whistle and flute": "Suit"
}
return rhymes.get(rhyme.lower(), "Rhyme not found")
Another useful variation if you don't know the content of the dict and want to ensure a value is always returned:
v = adict.get('whatever') or 'default'
Would get a default value even if a there was a key with a None value in the dict

Greatest Small date

I have a two date columns let's say A and B in two separate tables. A contains the information of the date of test and column B contains date at which the factory was calibrated. I want to extract information of how many days has been passed since the factory was last calibrated.
For example:
A=['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29']
B=['2020-02-24', '2020-02-28']
Days_Passed since last calibration corresponding to A are [2,3,0,1]
Take the smallest date as reference 0 and convert other dates into days with respect to 0(smallest date)
A = [2,3,4,5]
B = [0,4]
for each value of A, perform a binary search to find the nearest smallest or equal value in B... Their subtraction will be the Days_Passed since the last calibration.
Answer Array = [2,3,0,1].
if dates in A and B be in order, this could be done in O(n+m) where n and m are the length of A and B. though you didn't mention about the programming language, this is the implementation in C#
the main part:
foreach (var testedDate in testedDates)
{
if (nextCalibratedDate.HasValue && (testedDate - nextCalibratedDate.Value).Days >= 0)
{
Console.WriteLine((testedDate - nextCalibratedDate.Value).Days);
calibratedDate = nextCalibratedDate.Value;
if (enumerator.MoveNext())
{
nextCalibratedDate = (DateTime?)enumerator.Current;
}
}
else
{
Console.WriteLine((testedDate - calibratedDate).Days);
}
}
and this is the complete code:
public static void Main(string[] args)
{
string[] A = new[] { "2020-02-26", "2020-02-27", "2020-02-28", "2020-02-29" };
string[] B = new[] { "2020-02-24", "2020-02-28" };
var testedDates = A
.Select(x => DateTime.Parse(x))
.ToArray();
var calibratedDates = B
.Select(x => DateTime.Parse(x))
.ToArray();
var enumerator = calibratedDates.GetEnumerator();
enumerator.MoveNext();
var calibratedDate = (DateTime)enumerator.Current;
DateTime? nextCalibratedDate = default;
if (enumerator.MoveNext())
{
nextCalibratedDate = (DateTime?)enumerator.Current;
}
foreach (var testedDate in testedDates)
{
if (nextCalibratedDate.HasValue && (testedDate - nextCalibratedDate.Value).Days >= 0)
{
Console.WriteLine((testedDate - nextCalibratedDate.Value).Days);
calibratedDate = nextCalibratedDate.Value;
if (enumerator.MoveNext())
{
nextCalibratedDate = (DateTime?)enumerator.Current;
}
}
else
{
Console.WriteLine((testedDate - calibratedDate).Days);
}
}
}

Swift range exceeds data length

I have a python server that I write and read from, using the stream delegate. It works fine but when I start a match and the server sends data back it crashes.
Here's where it crashes:
func checkForMessages() {
while true {
if inputBuffer.length < 4 {
print("buffer length\(inputBuffer.length)")
print( MemoryLayout.size(ofValue: Int()))
print("application quit here")
return
}
var msgLength = (inputBuffer.bytes).load(as: UInt32.self)
msgLength = UInt32(bigEndian: msgLength)
print(inputBuffer.length)
print(msgLength)
if inputBuffer.length < msgLength {
print("its returning here!")
return
}
// ******Crashes on the line Below******
let message: Data? = inputBuffer.subdata(with: NSRange(location: 4, length: Int(msgLength)))
processMessage(message!)
let amtRemaining: Int = inputBuffer.length - Int(msgLength) - 4
if amtRemaining == 0 {
inputBuffer = NSMutableData()
}
else {
print("Creating input buffer of length \(amtRemaining)")
inputBuffer = NSMutableData(bytes: inputBuffer.bytes + 4 + Int(msgLength), length: amtRemaining)
}
}
}
It crashes when setting "let message".
I have tried a couple of things like trying to mess with the range itself but I'm just not quite sure why its doing what its doing, I can post the server code used to send the message back if needed.
So the problem was fixed by replacing the following part of the code:
if inputBuffer.length < msgLength {
return
}
with
if inputBuffer.length < msgLength + 4 {
return
}

hex/binary string conversion in Swift

Python has two very useful library method (binascii.a2b_hex(keyStr) and binascii.hexlify(keyBytes)) which I have been struggling with in Swift. Is there anything readily available in Swift. If not, how would one implement it? Given all the bounds and other checks (like even-length key) are done.
Data from Swift 3 has no "built-in" method to print its contents as
a hex string, or to create a Data value from a hex string.
"Data to hex string" methods can be found e.g. at How to convert Data to hex string in swift or How can I print the content of a variable of type Data using Swift? or converting String to Data in swift 3.0. Here is an implementation from the first link:
extension Data {
func hexEncodedString() -> String {
return map { String(format: "%02hhx", $0) }.joined()
}
}
Here is a possible implementation of the reverse "hex string to Data"
conversion (taken from Hex String to Bytes (NSData) on Code Review, translated to Swift 3 and improved)
as a failable inititializer:
extension Data {
init?(fromHexEncodedString string: String) {
// Convert 0 ... 9, a ... f, A ...F to their decimal value,
// return nil for all other input characters
func decodeNibble(u: UInt8) -> UInt8? {
switch(u) {
case 0x30 ... 0x39:
return u - 0x30
case 0x41 ... 0x46:
return u - 0x41 + 10
case 0x61 ... 0x66:
return u - 0x61 + 10
default:
return nil
}
}
self.init(capacity: string.utf8.count/2)
var iter = string.utf8.makeIterator()
while let c1 = iter.next() {
guard
let val1 = decodeNibble(u: c1),
let c2 = iter.next(),
let val2 = decodeNibble(u: c2)
else { return nil }
self.append(val1 << 4 + val2)
}
}
}
Example:
// Hex string to Data:
if let data = Data(fromHexEncodedString: "0002468A13579BFF") {
let idata = Data(data.map { 255 - $0 })
// Data to hex string:
print(idata.hexEncodedString()) // fffdb975eca86400
} else {
print("invalid hex string")
}
Not really familiar with Python and the checks it performs when convert the numbers, but you can expand the function below:
func convert(_ str: String, fromRadix r1: Int, toRadix r2: Int) -> String? {
if let num = Int(str, radix: r1) {
return String(num, radix: r2)
} else {
return nil
}
}
convert("11111111", fromRadix: 2, toRadix: 16)
convert("ff", fromRadix: 16, toRadix: 2)
Swift 2
extension NSData {
class func dataFromHexString(hex: String) -> NSData? {
let regex = try! NSRegularExpression(pattern: "^[0-9a-zA-Z]*$", options: .CaseInsensitive)
let validate = regex.firstMatchInString(hex, options: NSMatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: hex.characters.count))
if validate == nil || hex.characters.count % 2 != 0 {
return nil
}
let data = NSMutableData()
for i in 0..<hex.characters.count/2 {
let hexStr = hex.substring(i * 2, length: 2)
var ch: UInt32 = 0
NSScanner(string: hexStr).scanHexInt(&ch)
data.appendBytes(&ch, length: 1)
}
return data
}
}
let a = 0xabcd1234
print(String(format: "%x", a)) // Hex to String
NSData.dataFromHexString("abcd1234") // String to hex

Categories