I have this python dictionary
dct = {'A': ['B', 'C'], 'B': ['D'], 'D': ['E'], 'C': ['F'], 'E': ['G']}
and i need a function to return it as
(A(B(D(E(G)))))(C(F))
I am unable to map the elements of each values to their own values. Any help would be appreciated.
Thank you
I'm not good at Python. I developed the function you want in Java. Hope you can convert it easily to Python.
import java.util.HashMap;
import java.util.Map;
public class MapTheMap {
// Count of open parentheses
static int parentheses = 0;
public static void main(String[] args) {
// Creating the map (i.e. dictionary in python)
Map<Character, Character[]> map = new HashMap<>();
map.put('A', new Character[]{'B', 'C'});
map.put('B', new Character[]{'D'});
map.put('D', new Character[]{'E'});
map.put('C', new Character[]{'F'});
map.put('E', new Character[]{'G'});
// The start key is A, you can develop a logic to get the first key if you want to
Character key = 'A';
System.out.print("(" + key);
recursion(map, key);
}
public static void recursion(Map<Character, Character[]> map, Character key) {
// If the map contains the key, add 1 parenthesis, print the value of that key, and call the function again with value as a key (Call 1: Key A -> Value B -- Call 2: Key B --> ...)
if (map.containsKey(key)) {
for (Character valueKey : map.get(key)) {
parentheses++;
System.out.print("(" + valueKey);
recursion(map, valueKey);
}
}
// If the map doesn't contain the key, print close parentheses
else {
while (parentheses >= 0) {
System.out.print(")");
parentheses--;
}
}
}
}
If there is something you don't understand, tell me and I'll try to edit the answer.
Related
How to put the results of this if condition in a array list?
import java.util.ArrayList;
import java.util.Scanner;
public class GreatestCommonDivisor {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a value whose GCD to be computed");
int number = scan.nextInt();
for(int i=1;i<=10;i++) {
if(number%i==0) {
ArrayList<Integer> arr = new ArrayList<Integer>(number) {
}
}
}
}
}
GCD stands for Greatest Common Divisor...which finds the greatest number that divides all the numbers that you specify, but in your code I just see one number.
So from your code I get the idea that you wish to find all the numbers less than 10 (inclusive) that divide number and store those numbers in an arraylist. Assuming my assumption to be correct you can do the following.
Declare your arraylist before the loop:
ArrayList<Integer>arr = new ArrayList<Integer>()
Now run the loop:
for(int i=1;i<=10;i++){
if(number%i==0){
v.add(i);
}
}
i search many place, did not find any solution.
so the question is.
i want a map in dart like this
var Map<String, String> data;
it will be a params init and passed in other place. but when pass the params, i want to limit the key in map only accept some special strings. like 'someA', 'someB'.
so,when call the function it like this.
functionA({'someA': 'xxxx', 'someB': 'xxxx'})
no other keys.
and also when i call the function i can just type some word and the IDE will show suggestion for me to select the key.
the all code like this (can not run).
var List<String> keyList = ['someA', 'someB'];
class Abc {
functionA({Map<valueOf keyList, String> data) {
}
}
Abc().functionA({'someA': 'xxxx', 'someB': 'xxxx'});
You can provide your own Map implementation (deriving from DelegatingMap from package:collection would make it a lot easier) and then override operator []= to throw if the supplied key should not be allowed. For example:
import 'package:collection/collection.dart';
/// A [Map] that allows only certain keys.
class LimitedMap<K, V> extends DelegatingMap<K, V> {
LimitedMap({Iterable<K> allowedKeys})
: allowedKeys = <K>{...allowedKeys},
super(<K, V>{});
final Set<K> allowedKeys;
/// Throws an exception if [key] is not allowed.
void _checkKey(K key) {
if (!allowedKeys.contains(key)) {
throw Exception('Invalid key: $key');
}
}
#override
void addAll(Map<K, V> other) => addEntries(other.entries);
#override
void addEntries(Iterable<MapEntry<K, V>> entries) {
for (var entry in entries) {
this[entry.key] = entry.value;
}
}
#override
V putIfAbsent(K key, V Function() ifAbsent) {
_checkKey(key);
return super.putIfAbsent(key, ifAbsent);
}
#override
V update(K key, V Function(V) update, {V Function() ifAbsent}) {
_checkKey(key);
return super.update(key, update, ifAbsent: ifAbsent);
}
#override
void operator []=(K key, V value) {
_checkKey(key);
super[key] = value;
}
}
class MyMap extends LimitedMap<String, String> {
MyMap([Map<String, String> initialMap])
: super(allowedKeys: {'foo', 'bar', 'baz'}) {
if (initialMap != null) {
addAll(initialMap);
}
}
}
Alternatively, if your keys are fixed, it'd be better to just make them properties on a custom class, and then you also would get the IDE autocompletion behavior that you want.
As these questions point out, Guid.NewGuid will return the same value for all rows due to the enforced deterministic nature of U-SQL i.e if it's scaled out if an element (vertex) needs retrying then it should return the same value....
Guid.NewGuid() always return same Guid for all rows
auto_increment in U-SQL
However.... the code example in the officials documentation for a User Defined Extractor purposefully uses Guid.NewGuid().
I'm not querying the validity of the answers for the questions above, as they are from an authoritative source (the programme manager for u-sql, so very authoritative!). However, what I'm wondering if the action of using an Extractor means NewGuid can be used as normal? Is it simply within c# expressions in u-sql and User Defined Functions in which NewGuid is unsafe?
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class FullDescriptionExtractor : IExtractor
{
private Encoding _encoding;
private byte[] _row_delim;
private char _col_delim;
public FullDescriptionExtractor(Encoding encoding, string row_delim = "\r\n", char col_delim = '\t')
{
this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding);
this._row_delim = this._encoding.GetBytes(row_delim);
this._col_delim = col_delim;
}
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
string line;
//Read the input line by line
foreach (Stream current in input.Split(_encoding.GetBytes("\r\n")))
{
using (System.IO.StreamReader streamReader = new StreamReader(current, this._encoding))
{
line = streamReader.ReadToEnd().Trim();
//Split the input by the column delimiter
string[] parts = line.Split(this._col_delim);
int count = 0; // start with first column
foreach (string part in parts)
{
if (count == 0)
{ // for column “guid”, re-generated guid
Guid new_guid = Guid.NewGuid();
output.Set<Guid>(count, new_guid);
}
else if (count == 2)
{
// for column “user”, convert to UPPER case
output.Set<string>(count, part.ToUpper());
}
else
{
// keep the rest of the columns as-is
output.Set<string>(count, part);
}
count += 1;
}
}
yield return output.AsReadOnly();
}
yield break;
}
}
https://learn.microsoft.com/en-us/azure/data-lake-analytics/data-lake-analytics-u-sql-programmability-guide#use-user-defined-extractors
I have an object as following :
public Class MyObjDTO {
private Long id;
private Boolean checked;
//getter and setters
#Override
public final int hashCode() {
Long id = getId();
return (id == null ? super.hashCode() : id.hashCode());
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (!(obj instanceof MyObjDTO))
return false;
Long id = getId();
Long objId = ((MyObjDTO) obj).getId();
if (id.equals(objId)) {
return true;
} else {
return false;
}
}
}
And I have two hash sets containing some instances from this object :
HashSet oldSet = new HashSet();
oldSet.add(new MyObjDTO(1,true));
oldSet.add(new MyObjDTO(2,true));
oldSet.add(new MyObjDTO(3,false));
HashSet newSet = new HashSet();
newSet.add(new MyObjDTO(1,false));
newSet.add(new MyObjDTO(2,true));
newSet.add(new MyObjDTO(4,true));
So what I want to do here is to select objects that are in the newSet and not in the oldSet, in this case its : new MyObjDTO(4,true) which I did using this :
Stream<MyObjDTO> toInsert = newSet.stream().filter(e -> !oldSet.contains(e));
Then I want to select objects that are in the oldSet and not in the newSet, in this case its :new MyObjDTO(3,false) which I did using this :
Stream<MyObjDTO> toRemove = oldSet.stream().filter(e -> !newSet.contains(e));
The last step is that I want to select the objects that are in both newSet and oldSet but they have a different value for the attribute checked , in this case it's : new MyObjDTO(1,false).
What I tried is this :
Stream<MyObjDTO> toUpdate = oldSet.stream().filter(newSet::contains);
But this one will return both new MyObjDTO(1,false) and new MyObjDTO(2,true).
How can I solve this ?
One way is to first use a map and then adjust your filter condition:
Map<MyObjDTO, Boolean> map = newSet.stream()
.collect(Collectors.toMap(Function.identity(), MyObjDTO::getChecked));
Stream<MyObjDTO> toUpdate = oldSet.stream()
.filter(old -> newSet.contains(old) && old.getChecked() != map.get(old));
Firstly, your equals() and hashCode() methods violate their basic contract. As per the javadoc of hashCode():
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
Your implementation of hashCode() does not follow this contract. Your first step should be to fix that.
Secondly, since Java 1.2 (nearly 20 years ago), java has provided the method removeAll() that does exactly what you want to do for the first part:
// Given these 2 sets:
HashSet<MyObjDTO> oldSet = new HashSet<>();
HashSet<MyObjDTO> newSet = new HashSet<>();
HashSet<MyObjDTO> onlyInNew = new HashSet<>(newSet);
onlyInNew.removeAll(oldSet);
// similar for onlyInOld
For the second part, you'll need to create a Map to find and get the object out:
Map<MyObjDTO, MyObjDTO> map = new HashMap<>O;
oldSet.forEach(o -> map.put(o, o);
HashSet<MyObjDTO> updated = new HashSet<>(newSet);
updated.removeIf(o -> oldSet.contains(o) && o.getChecked()() != map.get(o).getChecked());
In the last step, you rely on the equals() method of the DTO :
Stream<FonctionnaliteDTO> toUpdate = oldSet.stream().filter(newSet::contains);
The method uses only the id field to determinate object equality.
You don't want to do that.
You want to filter on a specific field : checked.
Besides, you should perform the operation on the result of the intersection of the two Sets.
Note that you should use simply Collection.retainAll() to compute the intersection between two collections:
Set<MyObjDTO> set = ...
Set<MyObjDTO> setTwo = ...
set.retainAll(setTwo);
Then you can filter objects that have both same id and checked value by using a double loop : for + iterator.
for (MyObjDTO dto : set){
for (Iterator<MyObjDTO> it = set.iterator(); it.hasNext();){
MyObjDTO otherDto = it.next();
if (otherDto.getId().equals(dto.getId()) &&
otherDto.getChecked() == dto.getChecked()){
it.remove();
}
}
}
You could do that with Stream but IHMO it could be less readable.
I think I need some feedback on my collection classes - still learning typescript and javascript and these implementations can surely be improved. I am looking forward to any suggestion. I think I do use the generic types in a useful way, any advice here would be appreciated.
The answer I am looking for most is removing the duplicate IHashTable definition from the end of both snippets and moving it to its own file, I cannot get that done it seems. I am even unsure if this IS an interface in the first place. It compiles and works this way, as far as I can see.
The collection types are incomplete and only define the basic most function at the moment. Once I am sure I use the language and its features correct the other functions should not be too difficult.
Here is my HashSet:
import { IHashable } from "./IHashable"
export class HashSet<T extends IHashable> {
private _items: HashTable<T>;
public constructor() {
this._items = {};
}
public Add(key: T): void {
let str: string = key.GetHash();
if (this._items[str] == null) {
this._items[str] = key;
}
else {
throw new RangeError("Key '" + str + "' already exists.");
}
}
public Contains(key: T): boolean {
let str: string = key.GetHash();
return this._items[str] != null;
}
}
interface HashTable<T> {
[key: string]: T;
}
I wonder if I can avoid the checking-before-adding in a way. The javascript-dictionary this relies on does allow duplicates, so to avoid them there is no other way than to check myself?
This is my Dictionary:
import { IHashable } from "./IHashable"
export class Dictionary<T1 extends IHashable, T2> {
private _items: HashTable<KeyValuePair<T1, T2>>;
public constructor() {
this._items = {};
}
public Add(key: T1, value: T2) {
let str: string = key.GetHash();
if (this._items[str] == null) {
let kvp: KeyValuePair<T1, T2> = new KeyValuePair(key, value);
this._items[str] = kvp;
}
else {
throw new RangeError("Key '" + str + "' already exists.");
}
}
public ContainsKey(key: T1): boolean {
let str: string = key.GetHash();
return this._items[str] != null;
}
public Get(key: T1): T2 {
let str: string = key.GetHash();
let kvp: KeyValuePair<T1, T2> = this._items[str];
if (kvp == null) throw new RangeError("Key '" + str + "' not found")
return kvp.Value;
}
}
export class KeyValuePair<T1 extends IHashable, T2> {
private _key: T1;
private _value: T2;
public get Key(): T1 { return this._key; }
public get Value(): T2 { return this._value; }
public constructor(key: T1, value: T2) {
this._key = key;
this._value = value;
}
}
interface HashTable<T> {
[key: string]: T;
}
Both rely on a definition of IHashable (hashABLE and hashTABLE: I should find other names.)
export interface IHashable {
GetHash(): string;
}
The dictionary looks a bit strange, it "wraps" my dictionary into a new type KeyValuePair and then uses this in the javascript dictionary. What I hope to gain by doing this is get my own type for key, in and out, as long as it offers a string by which it can be indexed. - No idea if that makes sense or is completly wrong.
What I am missing is the count of items in the collection, a way to remove items, and a way to iterate over the keys and the values.
Regarding iterating over I will post another question with my implementation of a list and a ForEach over it, hoping iterating the keys or values might be possible in the same way.
Probably the most important question I forgot here: How could the GetHash-Method be build for an own class? I was going to have a static number on my classes, and count up by 1 in the constructor before assign this number to each instance. This would guarantee uniqueness... is there something better?
Thanks for any tip!
Ralf